import 'dart:async';
import 'dart:io';

import 'package:cookie_jar/cookie_jar.dart';
import 'package:dio/dio.dart';
import 'package:dio_cookie_manager/dio_cookie_manager.dart';
import 'package:flutter/material.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:oktoast/oktoast.dart';
import 'package:path_provider/path_provider.dart';
import 'package:stage_app/constants/constant.dart';
import 'package:stage_app/generated/json/base/json_convert_content.dart';
import 'package:stage_app/wigets/common/loading.dart';

Map<String, dynamic> optHeader = {
  'accept-language': 'zh-cn',
  'content-type': 'application/json'
};

var dio = new Dio(BaseOptions(connectTimeout: 30000, headers: optHeader));

class HttpUtils {
  static Future get(String url, [Map<String, dynamic> params]) async {
    /// 日志
    if (!Constant.IS_PROD) {
      dio.interceptors
          .add(LogInterceptor(requestBody: true, responseBody: true)); //开启请求日志
    }
    var response;

    // 设置代理 便于本地 charles 抓包
    // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (HttpClient client) {
    //   client.findProxy = (uri) {
    //     return "PROXY 30.10.24.79:8889";
    //   };
    // };

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    var cookieJar = PersistCookieJar(dir: appDocPath + "/.cookies/");
    dio.interceptors.add(CookieManager(cookieJar));
    if (params != null) {
      response = await dio.get(url, queryParameters: params);
    } else {
      response = await dio.get(url);
    }
    return response.data;
  }

  static Future post<T>(BuildContext context,String url, Map<String, dynamic> params) async {
    // // 设置代理 便于本地 charles 抓包
    // (dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate =
    //     (HttpClient client) {
    //   client.findProxy = (uri) {
    //     return "PROXY 30.10.24.79:8889";
    //   };
    // };
    /// 日志
    if (!Constant.IS_PROD) {
      dio.interceptors
          .add(LogInterceptor(requestBody: true, responseBody: true)); //开启请求日志
    }

    Loading.showProgress(context, child: SpinKitFadingCircle(
      itemBuilder: (_, int index) {
        return DecoratedBox(
          decoration: BoxDecoration(
            color: index.isEven ? Colors.red : Colors.green,
          ),
        );
      },
    ));

    Directory appDocDir = await getApplicationDocumentsDirectory();
    String appDocPath = appDocDir.path;
    var cookieJar = PersistCookieJar(dir: appDocPath + "/.cookies/");
    dio.interceptors.add(CookieManager(cookieJar));
    var response = await dio.post(url, data: params);
    print('请求结果 => ' + response.toString());
    Loading.dismiss(context);
    if(response.statusCode == 200){
      var data = response.data;
      if(data['code'] == 200){
        T fromJsonAsT = JsonConvert.fromJsonAsT<T>(data);
        return fromJsonAsT;
      }else{
        print('请求错误 => ' + data.toString());
        _showToast('${data['msg']}');
        return Future.error(data['msg']);
      }
    }
    _showToast('网络错误');
    return Future.error('网络错误');

  }

  static _showToast(String msg){
    showToast(
      msg,
      position: ToastPosition.bottom,
      backgroundColor: Colors.black.withOpacity(0.8),
      radius: 13.0,
      textStyle: TextStyle(fontSize: 18.0),
      animationBuilder: Miui10AnimBuilder(),
    );
  }
}
